﻿﻿﻿//======================================================================
//
//        Copyright : Zhengzhou Strawberry Computer Technology Co.,LTD.
//        All rights reserved
//        
//        Application:NFinal MVC framework
//        Filename :Router.cs
//        Description :路由类
//
//        created by Lucas at  2015-10-15`
//     
//        WebSite:http://www.nfinal.com
//
//======================================================================
using System;
using System.Collections.Generic;
using System.Web;
using System.Threading;
using System.Globalization;
using System.Collections.Specialized;
using System.Text.RegularExpressions;
namespace BlackHtml5
{
    public static class Router
    {
        public static string GetString(string val, string de)
        {
            return string.IsNullOrEmpty(val) ? de : val;
        }
        public static string UCFirst(string val)
        {
            CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
            return cultureInfo.TextInfo.ToTitleCase(val);
        }
		 private static void Callback(IAsyncResult result)
        {
            //结束异步写入
            System.IO.FileStream stream = (System.IO.FileStream)result.AsyncState;
            stream.EndWrite(result);
            stream.Close();
        }
		//设置浏览器缓存
        public static void SetBrowerCache(HttpContext context,int optimizing,int seconds)
        {
            //浏览器缓存
            if ((optimizing & 224) != 0)
            {
                context.Response.Cache.SetCacheability(HttpCacheability.Public);
                //NotModify
                if ((optimizing & 32) != 0)
                {
                    context.Response.Cache.SetLastModifiedFromFileDependencies();
                }
                //Expires
                else if ((optimizing & 64) != 0)
                {
                    context.Response.Cache.SetExpires(DateTime.Now.AddSeconds(seconds));
                }
                //NoExpires
                else if ((optimizing & 128) != 0)
                {
                }
            }
            else
            {
                //不进行缓存
                context.Response.Cache.SetNoStore();
            }
        }
        //设置服务器缓存
        public static void SetServerCacheAndOutPut(HttpContext context, string app, string urlWithOutAppAndExt, string url, byte[] buffer, int optimizing, int seconds)
        {
            //服务器缓存
            if ((optimizing & 14) != 0)
            {
                //FileDependency
                if ((optimizing & 2) != 0)
                {
                    string fileName = context.Server.MapPath(app + "/HTML" + urlWithOutAppAndExt + ".html");
                    //将HTML写入静态文件
                    if (!System.IO.File.Exists(fileName))
                    {
                        string dir = System.IO.Path.GetDirectoryName(fileName);
                        if (!System.IO.Directory.Exists(dir))
                        {
                            System.IO.Directory.CreateDirectory(dir);
                        }
                        System.IO.FileStream file = new System.IO.FileStream(fileName, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.ReadWrite, 1024, true);
                        file.BeginWrite(buffer, 0, buffer.Length, new AsyncCallback(Callback), file);
                    }
                    //将HTML插入新的缓存
                    System.Web.Caching.CacheDependency dep = new System.Web.Caching.CacheDependency(fileName);
                    HttpRuntime.Cache.Insert(url, buffer, dep, System.Web.Caching.Cache.NoAbsoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration);
                }
                //AbsoluteExpiration
                else if ((optimizing & 4) != 0)
                {
                    HttpRuntime.Cache.Insert(url, buffer, null, DateTime.Now.AddSeconds(seconds), System.Web.Caching.Cache.NoSlidingExpiration);
                }
                //SlidingExpiration
                else if ((optimizing & 8) != 0)
                {
                    HttpRuntime.Cache.Insert(url, buffer, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, 0, seconds));
                }
            }
            //直接输出
            context.Response.OutputStream.Write(buffer, 0, buffer.Length);
            context.Response.OutputStream.Close();
        }
        //写入缓存
        public static bool WriteCache(HttpContext context,string url,int optimizing)
        {
            object cache = null;
            //服务器缓存
            if ((optimizing & 14) != 0)
            {
                cache = HttpRuntime.Cache.Get(url);
                //如果缓存存在则直接输出.
                if (cache != null)
                {
                    System.IO.Stream stream = null;
                    if ((optimizing & 1536) != 0)
                    {
                        if ((optimizing & 512) != 0)
                        {
                            context.Response.AppendHeader("Content-encoding", "gzip");
                        }
                        else if ((optimizing & 1024) != 0)
                        {
                            context.Response.AppendHeader("Content-encoding", "deflate");
                        }
                    }
                    byte[] buffer= (byte[])cache;
                    context.Response.OutputStream.Write(buffer, 0, buffer.Length);
                    context.Response.OutputStream.Close();
                    return true;
                }
            }
            return false;
        }
        /// <summary>
        /// 计算actionUrl
        /// </summary>
        /// <param name="requestedPath"></param>
        /// <returns></returns>
        private static string GetActionUrl(string requestedPath)
        {
            int position = requestedPath.LastIndexOf('.');
            int pointer = 0;
            string actionUrl = "";
            if (position > 0)
            {
                bool hasGet = int.TryParse(requestedPath.Substring(position - 2, 2), out pointer);
                if (hasGet)
                {
                    actionUrl = requestedPath.Substring(0, pointer + 1);
                }
                else
                {
                    actionUrl = requestedPath;
                }
            }
            return actionUrl;
        }
        public static void Run(HttpContext context, string requestedPath)
        {
            //取出action标识
            int find = 0;
            string f = requestedPath.Substring(requestedPath.Length - 8, 5);
            int.TryParse(requestedPath.Substring(requestedPath.Length - 8, 5), out find);
            //去掉00000.htm后缀,还原requestPath
            requestedPath = requestedPath.Substring(0, requestedPath.Length - 8);
            string[] hostName = context.Request.Url.Host.ToString().Split('.');
            string subdomain = hostName.Length == 3 ? hostName[0] : "www";
            string[] parameters = null;
            NameValueCollection get = new NameValueCollection();
			//提取form参数
            if (context.Request.Form.Count > 0)
            {
                for (int i = 0; i < context.Request.Form.Count; i++)
                {
                    get.Add(context.Request.Form.Keys[i], context.Request.Form[i]);
                }
            }
			//提取URL?后的参数
			if (context.Request.QueryString.Count > 0)
            {
                for (int i = 0; i < context.Request.QueryString.Count; i++)
                {
                    get.Add(context.Request.QueryString.Keys[i], context.Request.QueryString[i]);
                }
            }
			//提取MethodType
			NFinal.MethodType methodType = NFinal.MethodType.NONE;
            switch (context.Request.HttpMethod)
            {
                case "POST":methodType = NFinal.MethodType.POST; break;
                case "GET":methodType = NFinal.MethodType.GET; break;
                case "DELETE":methodType = NFinal.MethodType.DELETE; break;
                case "PUT":methodType = NFinal.MethodType.PUT; break;
                case "AJAX":methodType = NFinal.MethodType.AJAX; break;
                default:methodType = NFinal.MethodType.NONE; break;
            }
            //获取actionUrl,用于获取参数
            string actionUrl = GetActionUrl(requestedPath);
            switch (find)
            {
					case 1:
					{
						context.Response.ContentType = "text/html;charset=utf-8";
						Regex regParameters = new Regex("/WebSite/Article/Case.html");
                        Match matParameters = regParameters.Match(requestedPath);
						WebSite.Web.Default.Article.CaseAction control= new WebSite.Web.Default.Article.CaseAction(context);
						control._methodType = methodType;
						control._context = context;
						control._subdomain = subdomain;
						control._url=requestedPath;
						control._get = get;
						control._app="/WebSite";
						control.Before();
						control.Case();
						control.After();
						control.Close();
						context.Response.End();
					}break;
					case 2:
					{
						context.Response.ContentType = "text/html;charset=utf-8";
						Regex regParameters = new Regex("/WebSite/Article/News.html");
                        Match matParameters = regParameters.Match(requestedPath);
						WebSite.Web.Default.Article.NewsAction control= new WebSite.Web.Default.Article.NewsAction(context);
						control._methodType = methodType;
						control._context = context;
						control._subdomain = subdomain;
						control._url=requestedPath;
						control._get = get;
						control._app="/WebSite";
						control.Before();
						control.News();
						control.After();
						control.Close();
						context.Response.End();
					}break;
					case 3:
					{
						context.Response.ContentType = "text/html;charset=utf-8";
						Regex regParameters = new Regex("/WebSite/IndexController/Index.html");
                        Match matParameters = regParameters.Match(requestedPath);
						WebSite.Web.Default.IndexController.IndexAction control= new WebSite.Web.Default.IndexController.IndexAction(context);
						control._methodType = methodType;
						control._context = context;
						control._subdomain = subdomain;
						control._url=requestedPath;
						control._get = get;
						control._app="/WebSite";
						control.Before();
						control.Index();
						control.After();
						control.Close();
						context.Response.End();
					}break;
					case 4:
					{
						context.Response.ContentType = "text/html;charset=utf-8";
						Regex regParameters = new Regex("/WebSite/Index/index.html");
                        Match matParameters = regParameters.Match(requestedPath);
						WebSite.Web.Default.Admin.Index.indexAction control= new WebSite.Web.Default.Admin.Index.indexAction(context);
						control._methodType = methodType;
						control._context = context;
						control._subdomain = subdomain;
						control._url=requestedPath;
						control._get = get;
						control._app="/WebSite";
						control.Before();
						control.index();
						control.After();
						control.Close();
						context.Response.End();
					}break;
					case 5:
					{
						context.Response.ContentType = "text/html;charset=utf-8";
						Regex regParameters = new Regex("/WebSite/Public/Success/([\\S]+)/([\\S]+)/([\\S]+)23.html");
                        Match matParameters = regParameters.Match(requestedPath);
						if (get["message"] == null)
                        {
                            get.Add("message", matParameters.Groups[1].Value);
                        }
                        else
                        {
                            get["message"] = matParameters.Groups[1].Value;
                        }
						if (get["url"] == null)
                        {
                            get.Add("url", matParameters.Groups[2].Value);
                        }
                        else
                        {
                            get["url"] = matParameters.Groups[2].Value;
                        }
						if (get["second"] == null)
                        {
                            get.Add("second", matParameters.Groups[3].Value);
                        }
                        else
                        {
                            get["second"] = matParameters.Groups[3].Value;
                        }
						WebSite.Web.Default.Common.Public.SuccessAction control= new WebSite.Web.Default.Common.Public.SuccessAction(context);
							string message=get["message"]==null?null:get["message"];
							string url=get["url"]==null?null:get["url"];
							int second=int.TryParse(get["second"],out second)?second:0;
						control._methodType = methodType;
						control._context = context;
						control._subdomain = subdomain;
						control._url=requestedPath;
						control._get = get;
						control._app="/WebSite";
						control.Before();
						control.Success(message,url,second);
						control.After();
						control.Close();
						context.Response.End();
					}break;
					case 6:
					{
						context.Response.ContentType = "text/html;charset=utf-8";
						Regex regParameters = new Regex("/WebSite/Public/Error/([\\S]+)/([\\S]+)/([\\S]+)21.html");
                        Match matParameters = regParameters.Match(requestedPath);
						if (get["message"] == null)
                        {
                            get.Add("message", matParameters.Groups[1].Value);
                        }
                        else
                        {
                            get["message"] = matParameters.Groups[1].Value;
                        }
						if (get["url"] == null)
                        {
                            get.Add("url", matParameters.Groups[2].Value);
                        }
                        else
                        {
                            get["url"] = matParameters.Groups[2].Value;
                        }
						if (get["second"] == null)
                        {
                            get.Add("second", matParameters.Groups[3].Value);
                        }
                        else
                        {
                            get["second"] = matParameters.Groups[3].Value;
                        }
						WebSite.Web.Default.Common.Public.ErrorAction control= new WebSite.Web.Default.Common.Public.ErrorAction(context);
							string message=get["message"]==null?null:get["message"];
							string url=get["url"]==null?null:get["url"];
							int second=int.TryParse(get["second"],out second)?second:0;
						control._methodType = methodType;
						control._context = context;
						control._subdomain = subdomain;
						control._url=requestedPath;
						control._get = get;
						control._app="/WebSite";
						control.Before();
						control.Error(message,url,second);
						control.After();
						control.Close();
						context.Response.End();
					}break;
					case 7:
					{
						context.Response.ContentType = "text/html;charset=utf-8";
						Regex regParameters = new Regex("/WebSite/Public/Header.html");
                        Match matParameters = regParameters.Match(requestedPath);
						WebSite.Web.Default.Common.Public.HeaderAction control= new WebSite.Web.Default.Common.Public.HeaderAction(context);
						control._methodType = methodType;
						control._context = context;
						control._subdomain = subdomain;
						control._url=requestedPath;
						control._get = get;
						control._app="/WebSite";
						control.Before();
						control.Header();
						control.After();
						control.Close();
						context.Response.End();
					}break;
					case 8:
					{
						context.Response.ContentType = "text/html;charset=utf-8";
						Regex regParameters = new Regex("/WebSite/Public/Footer.html");
                        Match matParameters = regParameters.Match(requestedPath);
						WebSite.Web.Default.Common.Public.FooterAction control= new WebSite.Web.Default.Common.Public.FooterAction(context);
						control._methodType = methodType;
						control._context = context;
						control._subdomain = subdomain;
						control._url=requestedPath;
						control._get = get;
						control._app="/WebSite";
						control.Before();
						control.Footer();
						control.After();
						control.Close();
						context.Response.End();
					}break;
					case 9:
					{
						context.Response.ContentType = "text/html;charset=utf-8";
						Regex regParameters = new Regex("/WebSite/Public/Navigator.html");
                        Match matParameters = regParameters.Match(requestedPath);
						WebSite.Web.Default.Common.Public.NavigatorAction control= new WebSite.Web.Default.Common.Public.NavigatorAction(context);
						control._methodType = methodType;
						control._context = context;
						control._subdomain = subdomain;
						control._url=requestedPath;
						control._get = get;
						control._app="/WebSite";
						control.Before();
						control.Navigator();
						control.After();
						control.Close();
						context.Response.End();
					}break;
					case 10:
					{
						context.Response.ContentType = "text/html;charset=utf-8";
						Regex regParameters = new Regex("/WebSite/Public/KindEditor.html");
                        Match matParameters = regParameters.Match(requestedPath);
						WebSite.Web.Default.Common.Public.KindEditorAction control= new WebSite.Web.Default.Common.Public.KindEditorAction(context);
						control._methodType = methodType;
						control._context = context;
						control._subdomain = subdomain;
						control._url=requestedPath;
						control._get = get;
						control._app="/WebSite";
						control.Before();
						control.KindEditor();
						control.After();
						control.Close();
						context.Response.End();
					}break;
					case 11:
					{
						context.Response.ContentType = "text/html;charset=utf-8";
						Regex regParameters = new Regex("/WebSite/Public/Dock.html");
                        Match matParameters = regParameters.Match(requestedPath);
						WebSite.Web.Default.Common.Public.DockAction control= new WebSite.Web.Default.Common.Public.DockAction(context);
						control._methodType = methodType;
						control._context = context;
						control._subdomain = subdomain;
						control._url=requestedPath;
						control._get = get;
						control._app="/WebSite";
						control.Before();
						control.Dock();
						control.After();
						control.Close();
						context.Response.End();
					}break;
					case 12:
					{
						context.Response.ContentType = "text/html;charset=utf-8";
						Regex regParameters = new Regex("/WebSite/VCode/GetVerifyImage.html");
                        Match matParameters = regParameters.Match(requestedPath);
						WebSite.Web.Default.Common.VCode.GetVerifyImageAction control= new WebSite.Web.Default.Common.VCode.GetVerifyImageAction(context);
						control._methodType = methodType;
						control._context = context;
						control._subdomain = subdomain;
						control._url=requestedPath;
						control._get = get;
						control._app="/WebSite";
						control.Before();
						control.GetVerifyImage();
						control.After();
						control.Close();
						context.Response.End();
					}break;
					case 13:
					{
						context.Response.ContentType = "text/html;charset=utf-8";
						Regex regParameters = new Regex("/WebSite/VCode/VCheck/([\\S]+)21.html");
                        Match matParameters = regParameters.Match(requestedPath);
						if (get["vcode"] == null)
                        {
                            get.Add("vcode", matParameters.Groups[1].Value);
                        }
                        else
                        {
                            get["vcode"] = matParameters.Groups[1].Value;
                        }
						WebSite.Web.Default.Common.VCode.VCheckAction control= new WebSite.Web.Default.Common.VCode.VCheckAction(context);
							string vcode=get["vcode"]==null?null:get["vcode"];
						control._methodType = methodType;
						control._context = context;
						control._subdomain = subdomain;
						control._url=requestedPath;
						control._get = get;
						control._app="/WebSite";
						control.Before();
						control.VCheck(vcode);
						control.After();
						control.Close();
						context.Response.End();
					}break;
                default: break;
            }
        }
    }
}